from django.utils.deprecation import MiddlewareMixin


from web import models
from s25 import settings
import datetime
from django.shortcuts import redirect


class Trace():
    def __init__(self):
        self.user = None
        self.price_police = None
        self.project = None


class AuthMiddleware(MiddlewareMixin):

    def process_request(self, request):
        """
        如果用户已经登录，则request中赋值
        """
        request.trace = Trace()
        user_id = request.session.get('user_id', 0)
        user_object = models.UserInfo.objects.filter(id=user_id).first()
        request.tracer.user = user_object

        """
        1.获取当前用户访问的url
        2.检查url是否在白名单中，如果不在则返回登录页面  
        """
        if request.path_info  in settings.WHITE_REGEX_URL_LIST:
            return

        if not request.trace.user:
            return redirect('login')

        # 登录成功之后，访问后台管理时：获取当前用户所拥有的额度
        # 方式一：免费额度在交易记录中存储

        # 获取当前用户id值最大（最近交易记录）
        _object = models.Transaction.objects.filter(user=user_object,status=2).order_by('-id').first()

        # 判断是否已过期
        current_time = datetime.datetime.now()
        if _object.end_datetime and _object.end_datetime< current_time:
                _object = models.Transaction.objects.filter(user=user_object,status=2,price_police__category=1).first()
        # request.transaction = _object
        request.tracer.price_police = _object.price_police


         # 方式2;免费的额度存储配置文件
        # 获取当前用户id值最大（最近交易记录）
        # _object = models.Transaction.objects.filter(user=user_object,status=2).order_by('-id').first()
        # if not _object:
             # 没有购买
        #     request.price_police = models.PricePolice.objects.filter(category=1,title="个人免费版").first()
        # else:
            # 付费版
            # current_time = datetime.datetime.now()
            # if _object.end_datetime and _object.end_datetime < current_time:
            #     request.price_police = models.PricePolice.objects.filter(category=1,title="个人免费版").first()
            # else:
            #     request.price_police = _object.price_police


    def process_view(self,request,view,args,kwargs):
        # 判断url是否是以manage开头，如果是则判断项目id是否是我创建或参与
        if not request.path_info.startswith('/manage'):
            return

        project_id = kwargs.get('project_id')
        # 是否是由我创建
        project_object = models.Project.objects.filter(creator=request.trace.user,id=project_id).first()
        if project_object:
            request.trace.user = project_object
            return

        # 是否是我参与的项目
        project_user_object = models.ProjectUser.objects.filter(user=request.trace.user,id=project_id).first()
        if project_user_object:
            request.tracer.user = project_user_object
            return
        return redirect('project_list')